import datetime
import logging
log = logging.getLogger("dbloader")

from google.appengine.ext import db
import statsdb

class RecordLoader(Loader):
  def __init__(self):
    Loader.__init__(self, 'Record',
                    [('date', lambda x: datetime.datetime.strptime(x, "%Y-%m-%d")),
                     ('dfmt', str),
                     ('value', float),
                     ('unit', str),
                     ('tags', lambda x: x.split(' '))
                     ])
    
  def HandleEntity(self, entity):
    #check if entity exists.
    query = statsdb.Record.gql("WHERE date = :1 and tags = :2",
                     entity.date, entity.tags)
    if query.count() > 0:
      log.warn("The Record[%s, %s] already exists, ignored",
               entity.date.strftime("%Y-%m-%d"), " ".join(entity.tags))
      return []
    #check if tags exists
    for t in entity.tags:
      if "date" == t:
        log.warn("\'date\' is not invalid tag at Record[%s, %s], ignored",
                 entity.date.strftime("%Y-%m-%d"), " ".join(entity.tags))
        return []
      query = statsdb.Tags.gql("WHERE name = :1", t)
      if 0 == query.count():
        tag = statsdb.Tags(name = t)
        tag.put()
    return entity    
